package com.eco.fanliapp.job.userjob;



import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.eco.fanliapp.entity.AppUser;
import com.eco.fanliapp.entity.SySendSm;
import com.eco.fanliapp.service.IAppUserRedRewardService;
import com.eco.fanliapp.service.IAppUserService;
import com.eco.fanliapp.service.ISmsService;
import com.eco.fanliapp.service.ISySendSmService;
import com.eco.fanliapp.utils.MessageUtils;
import com.eco.fanliapp.vo.AppUserRedRewardVo;
import org.apache.commons.collections.CollectionUtils;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.Serializable;
import java.util.List;


/**
 * 给用户发短信
 * 1.注册后3小时（复制链接任务发送短信，免单商品）
 * 2.首购红包到期前8小时提醒
 */
@DisallowConcurrentExecution
@PersistJobDataAfterExecution
public class SendPhoneMessageTask implements Job, Serializable {

    private static final Logger log = LoggerFactory.getLogger(SendPhoneMessageTask.class);
    @Autowired
    IAppUserService appUserService;
    @Autowired
    IAppUserRedRewardService appUserRedRewardService;
    @Autowired
    ISySendSmService sySendSmService;
    @Autowired
    private ISmsService smsService;


    public SendPhoneMessageTask() {
    }

    @Override
    public void execute(JobExecutionContext context)   {

        //取得job详情
        JobDetail jobDetail = context.getJobDetail();
        JobDataMap dataMap =  jobDetail.getJobDataMap();

        int executeCount = 0;
        if (dataMap.containsKey("runCount")) {
            executeCount = dataMap.getInt("runCount");
        }

        // 增量计数并将其存储回 JobDataMap，这样可以适当保持工作状态
        executeCount++;
        dataMap.put("runCount", executeCount);

        long startTime = System.currentTimeMillis();
        log.info("***************************************开始执行给用户发短信任务-HandleOpenIdTask：executeCount="+executeCount+"--startTime="+startTime);

        try {
            // 注册后3小时(首购红包，复制链接)
            sendRegistMesage();
            //首购红包到期前8小时提醒
            sendRedEnvelopesMessage();

        }catch (Exception e){
            e.printStackTrace();
            log.info("处理用户公众号下openId映射错误");
        }
        long endTime = System.currentTimeMillis();
        log.info("***************************************结束执行给用户发短信任务-HandleOpenIdTask：executeCount=" + executeCount + "--endTime=" + endTime + "--耗时=" + (endTime - startTime));

    }

    /**
     *  注册后3小时(首购红包，复制链接)
     */
    public void sendRegistMesage(){
        //查询新人红包未使用的用户(登陆时间<= 当前时间-5) （0.注册 1.有手机号 2.未发过短息 3.首购红包未过期，完成首购）
        Integer logType = 2;
        List<AppUser> fistList = appUserService.queryAppUserSm(logType);

        //查询免单未领取的用户(登陆时间<= 当前时间-5)
        logType = 3;
        List<AppUser> freeList = appUserService.queryAppUserSm(logType);

        //取即没完成首购，又未完成免单购买（取交集）
        freeList.retainAll(fistList);
        for(AppUser u1 : freeList){
            //发送短信
            //String content = "亲，您还5元新人红包和免单没有领取，快打开省鸭app完成新手任务领取叭~";
            String content = "您还5元新人红包和免单没有领取";
            String message = sendMessage(u1.getAlipayPhoneNumber(), content);
            saveMessageLog(u1.getUserId(),u1.getAlipayPhoneNumber(),content,0,0,message);

        }

        //未领取新人红包(但不包含发过消息的用户)
        fistList.removeAll(freeList);
        for (AppUser u2 : fistList){
            //发送短信
            //String content = "亲您还5元新人红包没有领取，快打开省鸭app完成新手任务领取叭~";
            String content = "您还5元新人红包没有领取";
            String message = sendMessage(u2.getAlipayPhoneNumber(), content);
            saveMessageLog(u2.getUserId(),u2.getAlipayPhoneNumber(),content,0,0,message);
        }

    }

    /**
     * 新人首购红包到期前8小时提醒
     */
    public void sendRedEnvelopesMessage(){
        Integer logType = 2;
        //没有发送注册短信的用户红包(24小时之内，大于当前日期8小时)
        List<AppUserRedRewardVo> list = appUserRedRewardService.queryUserRedRewardSm();
        for(AppUserRedRewardVo vo :list){
            //发送短信
            //String content = "亲，您的5元新人红包即将过期，快打开省鸭app完成新手任务领取叭~";
            String content = "您的5元新人红包即将过期";
            String message = sendMessage(vo.getAlipayPhoneNumber(), content);
            saveMessageLog(vo.getUserId(),vo.getAlipayPhoneNumber(),content,1,0,message);
        }

    }

    /**
     * 发送短信
     * @param phone
     * @param content
     * @return
     */
    public String sendMessage(String phone, String content){
        if(phone == null || "".equals(phone)){
            return "手机号为空";
        }
        if(content == null || "".equals(content)){
            return "电话号码为空";
        }
        log.info("发送消息的手机:{},消息内容：{}",phone,content);

        String resultMesage = null;
        try {
            //发送短信
            //resultMesage = MessageUtils.sendMesage(phone, content);
            resultMesage = smsService.sendSms5(phone,content);

        } catch (Exception e) {
            log.info("手机号:{},发送捕获异常",phone,resultMesage);
            e.printStackTrace();
        }
        log.info("手机号:{},发送结果：{}",phone,resultMesage);
        return resultMesage;
    }

    /**
     * 保存短信日志
     * @param userId
     * @param phone
     * @param content
     * @param logType
     * @param status
     * @param messageResult
     */
    public void saveMessageLog(Long userId,String phone,String content,Integer logType,Integer status,String messageResult){
            SySendSm sm = new SySendSm();
            sm.setUserId(userId);
            sm.setPhonenumber(phone);
            sm.setSmContent(content);
            sm.setLogType(logType);
            sm.setLogStatus(status);
            sm.setMessageRemark(messageResult);

            sySendSmService.save(sm);
            log.info("记录短信发送日志，用户id:{};电话:{};内容:{};类型:{}",userId,phone,content,logType);
    }


}
